package org.logistics;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.logistics.bean.ActivityMangager;
import org.logistics.bean.MapInforBean;
import org.logistics.main.LoginMainActivity;

import android.os.Bundle;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnCreateContextMenuListener;
import android.view.ViewGroup;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
/**
 * 删除了前面的啦
 * @author yimou
 * 显示车辆列表
 *
 */
public class CarListActivity extends Activity {

	private String TAG = "org.logistics.carlist";
	private List<MapInforBean> mapInforList = new ArrayList<MapInforBean>() ;
	private ListView listView ;
	
	List<Map<String, Object>> listItems = new ArrayList<Map<String, Object>>();
	
	String userAccount;
	
	protected void onCreate(Bundle savedInstanceState) {
		ActivityMangager.addActivity(this);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_car_list);
		
		Intent intent = new Intent();
		intent = getIntent();
		userAccount = intent.getStringExtra("userAccount");
		
		//请求服务器得到车辆信息
		try {
			 getLocalPlace();
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		int len = mapInforList.size();
		for(int i = 0 ; i < len ; i++){
			MapInforBean mifb = new MapInforBean();
			mifb = mapInforList.get(i);
			String ifOnline = null;
			if(mifb.isOnLine() == false ){
				ifOnline = "离线";
			}if(mifb.isOnLine() == true){
				ifOnline = "在线";
			}

		    Map<String , Object> listItem = new HashMap<String, Object>();
		    listItem.put("car_num", mifb.getCarNum().trim());
		    listItem.put("car_information_1", ifOnline.trim() + "  " + mifb.getSpeed()+ "km/h"
					+ "  "+ mifb.getLocationTime().trim() );
		    listItem.put("car_information_2", mifb.getAddress().trim());
		    listItems.add(listItem);
		}
		SimpleAdapter  simpleAdapter = new SimpleAdapter(this , listItems ,
				R.layout.car_list_item , 
				new String[]{"car_num" ,"car_information_1" ,
						"car_information_2" } , 
						new int[]{R.id.car_num , R.id.car_information_1
				,R.id.car_information_2});
		listView = (ListView) findViewById(R.id.car_list);
		listView.setAdapter(simpleAdapter);
		
		listView.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView parent, View view, int arg2,
					long arg3) {
				showInfo( parent,  view,  arg2, arg3);
				
				
			}
		});
		
		 
		//添加长按点击   
//        listView.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {
//			
//			@Override
//			public void onCreateContextMenu(ContextMenu menu, View v,
//					ContextMenuInfo menuInfo) {
//				
//				menu.setHeaderTitle("长按菜单-ContextMenu");      
//                menu.add(0, 0, 0, "弹出长按菜单0");   
//                menu.add(0, 1, 0, "弹出长按菜单1");  
//				
//			}
//		});

		
		
		
	}
	

	

	public void showInfo(AdapterView parent, View view, final int arg2,
			long arg3){
		String[] data = new String[] { "实时监控", "物理位置", "行驶轨迹" };
		AlertDialog.Builder builder = new AlertDialog.Builder(this);  
		builder.setTitle("功能列表")
		.setItems(data, new DialogInterface.OnClickListener() {
			
			public void onClick(DialogInterface dialog, int which) {
				Log.i(TAG, "int = "+which);
				String choice = String.valueOf(which);
				if(choice == "0" || choice.equals("0") ){
					//跳转到实时监控模式
					Intent intent = new Intent();
					intent.putExtra("userAccount", userAccount);
					intent.putExtra("centerNum", arg2);
					intent.setClass(CarListActivity.this, RealTimeMapActivity.class);
					startActivity(intent);
					
				}
				if(choice == "1" || choice.equals("1") ){
					String address = (String) listItems.get(arg2).get("car_information_2");
					Toast.makeText(getApplicationContext(), address,
	            		     Toast.LENGTH_SHORT).show();
				}
				if(choice == "2" || choice.equals("2") ){
					MapInforBean selected = mapInforList.get(arg2);
					String carImei = selected.getiMei();
					double mLat = selected.getH();
					double mLon =  selected.getI();
					Log.d(TAG, mLat + " in list");
					Log.d(TAG, mLon + " in list");
					Intent toReplayPathActivity = new Intent(CarListActivity.this, PlayBackHistoryPathActivity.class);
					toReplayPathActivity.putExtra("IMEI", carImei);
					toReplayPathActivity.putExtra("mLat", mLat);
					toReplayPathActivity.putExtra("mLon", mLon);
					startActivity(toReplayPathActivity);
				}
				
			}
		})
		.setNegativeButton("关闭", null)
		.show();


	}

	
 /**
   * 请求服务器获得数据 
   */
  public void getLocalPlace() throws JSONException, IllegalStateException, IOException{
	  BufferedReader in = null;
		/**
		 * 发送请求
		 */
		try {
			String request = "http://sj.jy100.com/GetRealtime2.ashx?userName="+userAccount+"&address=true";
			HttpClient hc = new DefaultHttpClient();
			HttpPost hp = new HttpPost(request);
			HttpResponse response = hc.execute(hp);  
	        in = new BufferedReader(  
	                new InputStreamReader(  
	                        response.getEntity().getContent()));  
	        StringBuffer string = new StringBuffer("");  
	        String lineStr = "";  
	        while ((lineStr = in.readLine()) != null) {  
	            string.append(lineStr + "\n");  
	        }  
	        in.close();  
	        String resultStr = string.toString();  
	        Log.i(TAG, resultStr);
	        
	        /**
	         * 解析字符串
	         */
	        JSONObject jo = new JSONObject(resultStr);
	        
	        /**
	         * 得到数据条数
	         * TotalCount
	         */
	        int totalCount = jo.getInt("TotalCount");
	        Log.i(TAG, "共有"+totalCount+"条数据");
	        
	        /**
	         * 把解析数据转保存在对象
	         */
	        JSONArray jsonList = jo.getJSONArray("RootResults");
	        for(int i = 0 ; i < totalCount ; i++  )
	        {
	        	JSONObject temp = new JSONObject(jsonList.getString(i));
	        	MapInforBean mifb = new MapInforBean();
	        	mifb.setCarNum(temp.getString("A"));
	        	mifb.setiMei(temp.getString("D"));
	        	mifb.setOnLine(temp.getBoolean("F"));
	        	mifb.setLocationTime(temp.getString("G"));
	        	mifb.setH(temp.getDouble("H"));
	        	mifb.setI(temp.getDouble("I"));
	        	mifb.setAngle(temp.getInt("K"));
	        	mifb.setSpeed(temp.getInt("J"));
	        	mifb.setMileage(temp.getDouble("L"));
	        	mifb.setStatue(temp.getString("M"));
	        	mifb.setAddress(temp.getString("O"));
	        	mapInforList.add(mifb);
	        }
			
		} catch (JSONException e) {
			Log.i(TAG, e.getMessage());
		}finally {  
          if (in != null) {  
              try {  
                  in.close();  
              } catch (IOException e) {  
                  e.printStackTrace();  
              }  
          }  
      }
  };

  
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.car_list, menu);
		return true;
	}

}


